
function resetTextareaForm() {
    $('#textarea-modal-title').html('Textarea');
    $('#textarea-save-btn').html('Create Textarea');
    
    $('#textarea-type').val('textarea');
    $('#textarea-guideline').val('none');
    $('#textarea-form').find('.guideline-control').slideUp();
    
    $('#textarea-label-text').val('');
    $('#textarea-name').val('');
    $('#textarea-id').val('');
    $('#textarea-placeholder').val('');
    $('#textarea-initial-value').val('');
    
    $('#textarea-type option.textarea').show();
    $('#textarea-type option.wysiwyg').show();
}

function toCLEditor() {
    $('#textarea-modal-title').html('CLEditor');
    $('#textarea-save-btn').html('Create CLEditor');
    
    $('#textarea-type').val('cleditor');
}

function toCKEditor() {
    $('#textarea-modal-title').html('CKEditor');
    $('#textarea-save-btn').html('Create CKEditor');
    
    $('#textarea-type').val('ckeditor');
}

$(function() {
    
    var cleditorSettings = {};
    var ckeditorSettings = {
        toolbarGroups: [
            {name: 'clipboard'},
            {name: 'editing'},
            {name: 'basicstyles'},
            {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi']},
            {name: 'styles'},
            {name: 'tools'}
        ]
    };
    
    // validation rules
    var rules = {};
    rules['label']                          = set_rules('label', 'label', 'required|maxlength[6]');
    rules['label-text']                     = set_rules('label-text', 'label-text', 'required|maxlength[25]');
    rules['bold-label']                     = set_rules('bold-label', 'bold-label', 'maxlength[25]');
    rules['name']                           = set_rules('name', 'name', 'required|maxlength[50]');
    rules['id']                             = set_rules('id', 'id', 'required|maxlength[50]');
    rules['placeholder']                    = set_rules('placeholder', 'placeholder', 'maxlength[50]');
    rules['initial-value']                  = set_rules('initial-value', 'initial-value', 'maxlength[255]');
    rules['type']                           = set_rules('type', 'type', 'maxlength[25]');
    rules['db-type']                        = set_rules('db-type', 'db-type', 'required|maxlength[25]');
    rules['min-length']                     = set_rules('min-length', 'min-length', 'numeric|maxlength[11]');
    rules['max-length']                     = set_rules('max-length', 'max-length', 'required|numeric|maxlength[11]');
    rules['show-list']                      = set_rules('show-list', 'show-list', 'maxlength[25]');
    rules['searchable']                     = set_rules('searchable', 'searchable', 'maxlength[25]');
    rules['show-api']                       = set_rules('show-api', 'show-api', 'maxlength[25]');
    rules['guideline']                      = set_rules('guideline', 'guideline', 'required|maxlength[50]');
    rules['guideline-title']                = set_rules('guideline-title', 'guideline-title', 'required|maxlength[50]');
    rules['guideline-text']                 = set_rules('guideline-text', 'guideline-text', 'required|maxlength[255]');
    rules['horizontal-size']                = set_rules('horizontal-size', 'horizontal-size', 'required|maxlength[25]');
    rules['position']                       = set_rules('position', 'position', 'required|maxlength[25]');

    // fieldset form validation
    $("#textarea-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
    
    resetTextareaForm();
    
    // show/hide label controls
    $('#textarea-label').change(function() {
        if( $(this).val() === 'none' ) {
            $('#textarea-form').find('.label-control').slideUp();
        } else {
            $('#textarea-form').find('.label-control').slideDown();
        }
    });
    
    // auto fill-up textarea name, id and placeholder using label text
    $('#textarea-label-text').change(function() {
        var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
        ( $('#textarea-name').val() === '' || $('#textarea-name').val() === undefined ) ? $('#textarea-name').val(textLabel) : '';
        ( $('#textarea-id').val() === '' || $('#textarea-id').val() === undefined ) ? $('#textarea-id').val(textLabel) : '';
        ( $('#textarea-placeholder').val() === '' || $('#textarea-placeholder').val() === undefined ) ? $('#textarea-placeholder').val( $(this).val() ) : '';
    });
    
    // auto fill-up textarea name, id and placeholder using label name
    $('#textarea-name').change(function() {
        if( $('#textarea-label').val() === 'none' ) {
            var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
            ( $('#textarea-id').val() === '' || $('#textarea-id').val() === undefined ) ? $('#textarea-id').val(textLabel) : '';
            ( $('#textarea-placeholder').val() === '' || $('#textarea-placeholder').val() === undefined ) ? $('#textarea-placeholder').val( $(this).val() ) : '';
        }
    });
    
    // show/hide guideline controls
    $('#textarea-guideline').change(function() {
        if( $(this).val() === 'none' ) {
            $('#textarea-form').find('.guideline-control').slideUp();
        } else if(  $(this).val() === 'label' ) {
            $('#textarea-form').find('.guideline-control').slideDown();
            $('#textarea-guideline-title-container').slideUp();
        } else {
            $('#textarea-form').find('.guideline-control').slideDown();
        }
    });
    
    // show/hide controls
    $('#textarea-type').change(function() {
        if( $(this).val() === 'textarea' ) {
            toTextarea();
        }
        if( $(this).val() === 'cleditor' ) {
            toCLEditor();
        }
        if( $(this).val() === 'ckeditor' ) {
            toCKEditor();
        }
    });
    
    $('#textarea-save-btn').click(function(event) {
        event.preventDefault();
        $('#textarea-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#textarea-form').valid()) {

            var values = $('#textarea-form').serializeJSON();
            
            // label
            var label                   = ( values['label'] !== undefined && values['label'] !== '' ) ? values['label'] : '';
            var labelPosition           = ( label !== '' || label !== 'none' ) ? ' align-' + label : 'none';
            var labelText               = ( values['label-text'] !== undefined && values['label-text'] !== '' ) ? values['label-text'] : '';
            
            // field data
            var fieldName               = ( values['name'] !== undefined && values['name'] !== '' ) ? values['name'] : '';
            var fieldId                 = ( values['id'] !== undefined && values['id'] !== '' ) ? values['id'] : '';
            var placeholder             = ( values['placeholder'] !== undefined && values['placeholder'] !== '' ) ? ' placeholder="' +values['placeholder']+ '"' : '';
            var initialValue            = ( values['initial-value'] !== undefined && values['initial-value'] !== '' ) ? ' value="' + values['initial-value'] + '"' : '';
            var type                    = ( values['type'] !== undefined && values['type'] !== '' ) ? values['type'] : '';
            
            // min and max length
            var minLength               = ( values['min-length'] !== undefined && values['min-length'] !== '') ? ' minlength="' + values['min-length'] + '"' : '';
            var maxLength               = ( values['max-length'] !== undefined && values['max-length'] !== '' ) ? ' maxlength="' + values['max-length'] + '"' : '';
            
            // guideline
            var guideline               = ( values['guideline'] !== undefined && values['guideline'] !== '' ) ? values['guideline'] : '';
            var guidelineTitle          = ( values['guideline-title'] !== undefined && values['guideline-title'] !== '' ) ? values['guideline-title'] : '';
            var guidelineText           = ( values['guideline-text'] !== undefined && values['guideline-text'] !== '' ) ? values['guideline-text'] : '';
            
            // size and position
            var horizontalSize          = ( values['horizontal-size'] !== undefined && values['horizontal-size'] !== '' ) ? ' ' + values['horizontal-size'] : '';
            var verticalSize            = ( values['vertical-size'] !== undefined && values['vertical-size'] !== '' )? ' ' + values['vertical-size'] : '';
            var position                = ( values['position'] !== undefined && values['position'] !== '' ) ? ' ' + values['position'] : '';
            
            // validations
            var validations             = values['validations'];
            var required                = $.inArray('required', validations) !== -1 ? ' required="true" ' : ' ';
            var requiredLabel           = ( $.inArray('required', validations) !== -1 && values['label'] !== '' && values['label'] !== 'none') ? ' *' : '';
            
            var markup = '';
            var list = $('<li class="form-group row"></li>');
            markup += '<button type="button" class="close" aria-hidden="true">&times;</button>\n';
            markup += '<label for="' +fieldId+ '" class="control-label' +labelPosition+ ' col-3">\n';
            markup += labelText + requiredLabel + '\n';
            markup += '<br><small>' +guidelineText+ '</small>\n';
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            markup += '<textarea name="' +fieldName+ '" id="' +fieldId+ '" class="form-control' + verticalSize + '"' + placeholder + initialValue + required + minLength + maxLength + '>' + initialValue + '</textarea>\n';
            markup += '</div>\n';
            markup += '</div>\n';
            
            list.html(markup);
            list.data('controls', values);
            
            $('#form-sortable li:first-child fieldset:first-child ul').prepend(list);
            
            // wysiwyg - cleditor
            if( type === 'cleditor' ) {
                $('#form-sortable li:first-child fieldset:first-child ul li:first-child textarea').cleditor(cleditorSettings);
            }
            
            // wysiwyg - ckeditor
            if( type === 'ckeditor' ) {
                CKEDITOR.replace( fieldId, ckeditorSettings );
//                $('#form-sortable li:first-child fieldset:first-child ul li:first-child textarea').cleditor();
            }
            
            $('#textarea-modal').modal('hide');

        }
        
        // submit form for validation purposes
        $('#textarea-form').submit();

    });
    
    // generic long text button
    $('#generic-longtext-btn').click(function() {
        resetTextareaForm();
        $('#textarea-type-container').show();
        $('#textarea-modal').modal({
            width: '95%'
        });
    });
    
    // textarea button
    $('#textarea-btn').click(function() {
        resetTextareaForm();
        $('#textarea-type option.textarea').hide();
        $('#textarea-type-container').hide();
        $('#textarea-modal').modal({
            width: '95%'
        });
    });
    
    // wysiwyg button
    $('#wysiwyg-btn').click(function() {
        resetTextareaForm();
        toCKEditor();
        $('#textarea-type option.textarea').hide();
        $('#textarea-type-container').show();
        $('#textarea-modal').modal({
            width: '95%'
        });
    });
    
});

